import React from 'react';
import {Card, Button, Form, Input, Select, Tree, Transfer, Modal, Alert, Icon, Divider, Popconfirm} from 'antd'
import axios from '../../components/Engineering/axios';
import ApiTubro from '../../components/Engineering/ApiTubro'
import QuickTool from '../../components/Engineering/QuickTool'
import SearchControl from '../../components/Engineering/SearchControl'
import ETable from '../../components/Engineering/ETable'
import Utils from '../../components/Engineering/utils'
import menuConfig from '../../config/router.config'

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;


export default class Main extends React.Component {
  state = {}
  page = {}


  searchFieldList = [
    {
      type: 'INPUT',
      label: '用户名',
      field: 'user_name',
      placeholder: '请输入用户名',
      //initialValue: '',
    },
    {
      type: 'INPUT',
      label: '用户名',
      field: 'user_name1',
      placeholder: '请输入用户名',
      //initialValue: '',
    },
    {
      type: 'INPUT',
      label: '用户名',
      field: 'user_name2',
      placeholder: '请输入用户名',
      //initialValue: '',
    },


  ]

  componentDidMount() {
    this.getListForPage();
  }

  getListForPage = params => ApiTubro.getListForPage.bind(this)('/role/list');

  // 角色提交
  handleRoleSubmit = () => {
    let data = this.roleForm.props.form.getFieldsValue();
    axios.ajax({url: '/role/create', params: data}).then((res) => {
      if (res) {
        this.setState({
          isRoleVisible: false
        })
        this.getListForPage();
      }
    })
  }

  //todo ---------------   处理权限   ---------------
  handlePermission = (customType, record) => {
    if (typeof customType == "string") {
      this.setPermissionData(record);
      return
    }
    ;
    if (!this.state.selectedRows) {
      Modal.info({title: '信息', content: '请选择一个角色'});
      return
    }
    this.setPermissionData(this.state.selectedRows[0])
    console.log(this.state.selectedRows[0],)

  }

  setPermissionData = (uniqueData) => {
    this.setState({
      isPermVisible: true,
      detailInfo: uniqueData,
      menuInfo: uniqueData.menus   //数据
    });
  }

  //设置菜单权限提交
  handlePermEditSubmit = () => {
    let data = this.roleForm.props.form.getFieldsValue();
    data.menus = this.state.menuInfo;
    console.log(data, "设置菜单权限提交数据")
    axios.ajax({url: '/permission/edit', params: data}).then((res) => {
      if (res) {
        this.setState({isPermVisible: false});
        this.getListForPage();
      }
    })
  }

  //todo ---------------   用户授权   ---------------
  handleUserAuth = (customType, record) => {
    if (typeof customType == "string") {
      return this.setUserAuthData(record)
    }
    if (!this.state.selectedRows) {
      return Modal.info({title: '信息', content: '未选中任何项目'})
    }
    this.setUserAuthData(this.state.selectedRows)
  }

  //获取用户授权字段
  setUserAuthData = (uniqueData) => {
    this.setState({
      isUserVisible: true,
      isAuthClosed: false,
      detailInfo: uniqueData,
      uniqueTableId: uniqueData.id
    });
    this.getRoleUserList(uniqueData.id);
  }

  getRoleUserList = (id) => {
    axios.ajax({url: '/role/user_list', params: {id: id, name: "随便瞎几把写,可以不写"}}).then((res) => {
      if (res) {
        this.getAuthUserList(res.result);
      }
    })
  }

  // 筛选目标用户
  getAuthUserList = (dataSource) => {
    const mockData = [];
    const targetKeys = [];
    if (dataSource && dataSource.length > 0) {
      for (let i = 0; i < dataSource.length; i++) {
        const data = {
          key: dataSource[i].user_id,
          title: dataSource[i].user_name,
          status: dataSource[i].status,
        };
        if (data.status == 1) {
          targetKeys.push(data.key);
        }
        mockData.push(data);
      }
    }
    this.setState({mockData, targetKeys});
  };


  // 用户授权提交
  handleUserSubmit = () => {
    let data = {};
    data.user_ids = this.state.targetKeys || [];
    data.role_id = this.state.uniqueTableId.id;
    // data.role_id = this.state.selectedRows.id;
    axios.ajax({url: '/role/user_role_edit', params: data}).then((res) => {
      if (res) {
        this.setState({isUserVisible: false})
        this.getListForPage();
      }
    })
  }

  render() {
    const columns = [
      {
        title: '角色ID',
        dataIndex: 'id'
      }, {
        title: '角色名称',
        dataIndex: 'role_name'
      }, {
        title: '创建时间',
        dataIndex: 'create_time',
        render: Utils.formatTime,
      }, {
        title: '使用状态',
        dataIndex: 'status',
        render: status => ["启用"][status] || "停用"
      }, {
        title: '授权时间',
        dataIndex: 'authorize_time',
        render: Utils.formatTime
      }, {
        title: '授权人',
        dataIndex: 'authorize_user_name',
      },
      {
        title: '操作',
        dataIndex: 'caozuo',
        key: 'caozuo',
        render: (text, record, index) => {
          return (
            <div>
              <a onClick={() => this.handlePermission.bind(this)("permission", record)}>
                <Icon type="edit" style={{marginRight: 2}}/>设置权限</a>

              <Divider type="vertical"/>
              <a onClick={() => this.handleUserAuth.bind(this)("authorization", record)}>
                <Icon type="delete" style={{marginRight: 2}}/>用户授权</a>{/* <Divider type="vertical"/> */}
              <Divider type="vertical"/>
              <Popconfirm
                placement="rightBottom"
                title="数据删除将不可以恢复,确定删除?"
                onConfirm={this.handleLineDelete}
                cancelText="否"
                okText="是"
              >
                <a href="">
                  <Icon type="delete" style={{marginRight: 2}}/>
                  删除
                </a>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return (
      <div>
        <Card style={{marginTop: 10}}>
          <SearchControl key="yansiji" searchFieldList={this.searchFieldList} {...ApiTubro.mapping(this)}/>
          <div style={{marginBottom: 10}}>
            <Button type="primary"
                    onClick={() => this.setState({
                      isRoleVisible: true
                    })}>
              创建角色
            </Button>

            <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
            <Button type="primary" onClick={this.handleUserAuth}>用户授权</Button>
            <Button style={{marginRight: 20}} type="primary" icon="plus">新建 </Button>

            {this.state.selectedRows ?
              <Button
                type="primary"
                onClick={this.handleMultipleDelect}
                disabled={!this.state.selectedRows}
                loading={this.state.loading}
                icon="delete"
              >
                批量删除
              </Button>
              :
              ''
            }
          </div>
          {this.state.selectedRows ? (
            <Alert
              message={`已选择 ${this.state.selectedRows &&
              this.state.selectedRows.length} 项  服务调用次数总计  ${this.state
                .selectedRows.length * 65} 万`}
              type="info"
              showIcon
            />
          ) : (
            <Alert message={`已选择 0 项  服务调用次数总计  0 万`} type="info" showIcon/>
          )}

          <div className="content-wrap" style={{marginTop: 20}}>
            <ETable
              rowSelection="checkbox"
              updateSelectedItem={Utils.updateSelectedItem.bind(this)}
              selectedRowKeys={this.state.selectedRowKeys}
              dataSource={this.state.pageListData}
              columns={columns}
              pagination={this.state.pagination}
            />
          </div>
        </Card>

        <Modal
          title="创建角色"
          visible={this.state.isRoleVisible}
          onOk={this.handleRoleSubmit}
          onCancel={() => {
            this.roleForm.props.form.resetFields();
            this.setState({
              isRoleVisible: false
            })
          }}
        >
          <RoleForm wrappedComponentRef={(inst) => this.roleForm = inst}/>
        </Modal>


        <Modal
          title="权限设置"
          visible={this.state.isPermVisible}
          width={600}
          onOk={this.handlePermEditSubmit}
          onCancel={() => {
            this.setState({isPermVisible: false})
          }}>
          <PermEditForm
            wrappedComponentRef={(inst) => this.roleForm = inst}
            detailInfo={this.state.detailInfo}
            menuInfo={this.state.menuInfo || []}   //todo 传给子组件选中的树列表
            patchMenuInfo={(checkedKeys) => {
              this.setState({menuInfo: checkedKeys});  //todo 通过子组件的回调函数触发父组件的方法，重新设置选中的树列表
            }}
          />
        </Modal>


        <Modal
          title="用户授权"
          visible={this.state.isUserVisible}
          width={800}
          cancelText="取消"
          okText="确定"
          onOk={this.handleUserSubmit}
          onCancel={() => {
            this.setState({isUserVisible: false})
          }}>
          <RoleAuthForm
            wrappedComponentRef={(inst) => this.userAuthForm = inst}
            isClosed={this.state.isAuthClosed}
            detailInfo={this.state.detailInfo}
            targetKeys={this.state.targetKeys}
            mockData={this.state.mockData}
            patchUserInfo={(targetKeys) => {
              this.setState({targetKeys: targetKeys})
            }}
          />
        </Modal>

      </div>
    );
  }
}


// 角色创建
class RoleForm extends React.Component {

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 16}
    };
    return (
      <Form layout="horizontal">
        <FormItem label="角色名称" {...formItemLayout}>
          {
            getFieldDecorator('role_name', {
              initialValue: ''
            })(
              <Input type="text" placeholder="请输入角色名称"/>
            )
          }
        </FormItem>
        <FormItem label="状态" {...formItemLayout}>
          {
            getFieldDecorator('state', {
              initialValue: 1
            })(
              <Select>
                <Option value={1}>开启</Option>
                <Option value={0}>关闭</Option>
              </Select>
            )}
        </FormItem>
      </Form>
    );
  }
}

RoleForm = Form.create({})(RoleForm);


// 设置权限
class PermEditForm extends React.Component {
  state = {};

  renderTreeNodes = (dataList, key = '') => {
    return dataList.map((item) => {
      let parentKey = key + item.name;
      if (item.routes) {
        return (
          <TreeNode title={item.name} key={parentKey} dataRef={item} className="op-role-tree">
            {this.renderTreeNodes(item.routes, parentKey)}
          </TreeNode>
        );
      } else if (item.btnList) {
        return (
          <TreeNode title={item.name} key={parentKey} dataRef={item} className="op-role-tree">
            {this.renderBtnTreedNode(item, parentKey)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={parentKey} dataRef={item} className="op-role-tree"/>;
    });
  };

  renderBtnTreedNode = (menu, parentKey = '') => {
    const btnTreeNode = []
    menu.btnList.forEach((item) => {
      btnTreeNode.push(<TreeNode title={item.name} key={parentKey + '-btn-' + item.key} className="op-role-tree"/>);
    })
    return btnTreeNode;
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}
    };
    const {detailInfo} = this.props;
    console.log(this.props, "dfkdjkf")
    return (
      <Form layout="horizontal">
        <FormItem label="角色名称：" {...formItemLayout}>
          <Input disabled maxLength={8} placeholder="请输入角色名称"
                 value={this.props.detailInfo && this.props.detailInfo.role_name}/>
        </FormItem>

        <FormItem label="状态：" {...formItemLayout}>
          {getFieldDecorator('status', {
            initialValue: '1'
          })(
            <Select style={{width: 80}} placeholder="启用">
              <Option value="1">启用</Option>
              <Option value="0">停用</Option>
            </Select>
          )}
        </FormItem>
        <Tree
          checkable
          // defaultExpandAll={true}
          // expandedKeys={[]}
          defaultExpandedKeys={["通用"]}
          autoExpandParent={true}
          onCheck={(checkedKeys) => this.props.patchMenuInfo(checkedKeys)}   //todo tree结构 回调函数,设置选中的节点，通过父组件方法再传递回来
          checkedKeys={this.props.menuInfo || []}
          // showLine
        >
          <TreeNode title="平台权限" key="【平台权限】">
            {this.renderTreeNodes(menuConfig)}
          </TreeNode>
        </Tree>
      </Form>
    )
  }
}

PermEditForm = Form.create({})(PermEditForm);


// 用户授权
class RoleAuthForm extends React.Component {

  filterOption = (inputValue, option) => {
    return option.title.indexOf(inputValue) > -1;
  };

  render() {
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}
    };
    const detail_info = this.props.detailInfo;
    return (
      <Form layout="horizontal">
        <FormItem label="角色名称：" {...formItemLayout}>
          <Input disabled maxLength={8} placeholder="请输入角色名称"
                 value={this.props.detailInfo && this.props.detailInfo.role_name}/>
        </FormItem>
        <FormItem label=" " colon={false} {...formItemLayout}>
          <Transfer
            locale={{itemUnit: '项', itemsUnit: '项', searchPlaceholder: '请输入搜索内容'}}
            titles={['待选用户', '已选用户']}
            searchPlaceholder={"输入用户名"}
            showSearch
            listStyle={{width: 200, height: 400}}
            dataSource={this.props.mockData}
            filterOption={this.filterOption}
            targetKeys={this.props.targetKeys}
            onChange={(targetKeys) => {
              this.props.patchUserInfo(targetKeys)
            }
            }
            render={item => item.title}
          />
        </FormItem>
      </Form>
    )
  }
}

RoleAuthForm = Form.create({})(RoleAuthForm);


// API#
// Tree props#
// 参数	                                说明	类型	默认值	版本
// autoExpandParent	                   是否自动展开父节点	boolean	true
// blockNode	                       是否节点占据一行	boolean	false	3.15.0
// checkable	                       节点前添加 Checkbox 复选框	boolean	false
// checkedKeys	                       (受控)选中复选框的树节点（注意：父子节点有关联，如果传入父节点 key，则子节点自动选中；相应当子节点 key 都传入，父节点也自动选中。当设置checkable和checkStrictly，它是一个有checked和halfChecked属性的对象，并且父子节点的选中与否不再关联	string[] | {checked: string[], halfChecked: string[]}	[]
// checkStrictly	                   checkable 状态下节点选择完全受控（父子节点选中状态不再关联）	boolean	false
// defaultExpandAll	                   默认展开所有树节点	boolean	false
// defaultExpandedKeys	               默认展开指定的树节点	string[]	[]
// defaultExpandParent	               默认展开父节点	bool	true	3.4.0
// defaultCheckedKeys	               默认选中复选框的树节点	string[]	[]
// defaultSelectedKeys	               默认选中的树节点	string[]	[]
// disabled	                           将树禁用	bool	false	3.4.0
// draggable	                       设置节点可拖拽（IE>8）	boolean	false
// expandedKeys	                       (受控)展开指定的树节点	string[]	[]
// filterTreeNode	                   按需筛选树节点（高亮），返回 true	function(node)	-
// loadData	                           异步加载数据	function(node)	-
// loadedKeys	                       (受控)已经加载的节点，需要配合 loadData 使用	string[]	[]	3.7.0
// multiple	                           支持点选多个节点（节点本身）	boolean	false
// selectedKeys	                       (受控)设置选中的树节点	string[]	-
// showIcon	                           是否展示 TreeNode title 前的图标，没有默认样式，如设置为 true，需要自行定义图标相关样式	boolean	false
// switcherIcon	                       自定义树节点的展开/折叠图标	React.ReactElement	-	3.12.0
// showLine	                           是否展示连接线	boolean	false
// onCheck	                           点击复选框触发	function(checkedKeys, e:{checked: bool, checkedNodes, node, event})	-
// onDragEnd	                       dragend 触发时调用	function({event, node})	-
// onDragEnter	                       dragenter 触发时调用	function({event, node, expandedKeys})	-
// onDragLeave	                       dragleave 触发时调用	function({event, node})	-
// onDragOver	                       dragover 触发时调用	function({event, node})	-
// onDragStart	                       开始拖拽时调用	function({event, node})	-
// onDrop	drop                       触发时调用	function({event, node, dragNode, dragNodesKeys})	-
// onExpand	                           展开/收起节点时触发	function(expandedKeys, {expanded: bool, node})	-
// onLoad	                           节点加载完毕时触发	function(loadedKeys, {event, node})	-	3.7.0
// onRightClick	                       响应右键点击	function({event, node})	-
// onSelect	                           点击树节点触发	function(selectedKeys, e:{selected: bool, selectedNodes, node, event})	-
// treeData	                           treeNodes 数据，如果设置则不需要手动构造 TreeNode 节点（key 在整个树范围内唯一）	array\<{key, title, children, [disabled, selectable]}>	-	3.19.8


// TreeNode props#
// 参数	                             说明	类型	默认值	版本
// checkable	                    当树为 checkable 时，设置独立节点是否展示 Checkbox	boolean	-	3.17.0
// disableCheckbox	                禁掉 checkbox	boolean	false
// disabled	                        禁掉响应	boolean	false
// icon	                            自定义图标。可接收组件，props 为当前节点 props	ReactNode/Function(props):ReactNode	-	3.4.0
// isLeaf	                        设置为叶子节点(设置了loadData时有效)	boolean	false
// key	                            被树的 (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys 属性所用。注意：整个树范围内的所有节点的 key 值不能重复！	string	内部计算出的节点位置
// selectable	                    设置节点是否可被选中	boolean	true
// title	                        标题	string|ReactNode	'---'
// DirectoryTree                    props#


// 参数	                            说明	类型	默认值	版本
// expandAction	                    目录展开逻辑，可选 false 'click' 'doubleClick'	string	click	3.7.0
